package com.yoo.ons.function.login

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.core.view.isVisible
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.google.gson.Gson
import com.yoo.ons.model.PolicyModel
import com.yoo.chat.kit.activity.RongWebviewActivity
import com.yoo.module_base.utils.SaveDeviceUtil
import com.yoo.module_base.utils.setOnClickCallback
import com.yoo.ons.BuildConfig
import com.yoo.ons.ToastUtil
import com.yoo.ons.base.BaseVMActivity
import com.yoo.ons.base.HttpRequestListener
import com.yoo.ons.databinding.ActivityLoginBinding
import com.yoo.ons.function.MainActivity
import com.yoo.ons.function.login.viewmodel.LoginViewModel
import com.yoo.ons.function.register.RegisterActivity
import com.yoo.ons.model.LoginResultModel
import com.yoo.ons.util.UserUtil
import io.reactivex.annotations.Nullable


/**
 * @Author andy
 * @Date 2024/5/29 10:07
 */
class LoginActivity : BaseVMActivity<ActivityLoginBinding, LoginViewModel>(
    ActivityLoginBinding::inflate,
    LoginViewModel::class.java
) {

    private val GOOGLE_SIGN_IN:Int = 1111
    private lateinit var googleSignInClient: GoogleSignInClient

    companion object {
        fun start(context: Context?,isDeleteAccount:Boolean?) {
            val intent = Intent(context, LoginActivity::class.java)
            isDeleteAccount?.let {
                intent.putExtra("isDeleteAccount",it)
            }
            context?.startActivity(intent)
        }
    }

    override fun initView() {
        super.initView()
        googleSignInClient = UserUtil.googleLogin(this)

        val source = intent.getBooleanExtra("isDeleteAccount",false)
        if (source) {
            binding.goBackContainer.isVisible = true
            Handler().postDelayed(Runnable {
                binding.goBackContainer.isVisible = false
            }, 5000)
        }


    }
    override fun initData() {
        //获取协议
        mViewModel?.getPolicy(object : HttpRequestListener<PolicyModel>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
                params["code"] = 2
            }

            override fun success(t: PolicyModel?) {
                SaveDeviceUtil.savePolicyUrl(Gson().toJson(t))
                t?.apply {
                    val style = SpannableStringBuilder()
                    style.append(getString(com.yoo.module_res.R.string.login_agreement_two))

                    style.setSpan(object : ClickableSpan() {
                        override fun onClick(p0: View) {
                            val intent = Intent(this@LoginActivity, RongWebviewActivity::class.java)
                            intent.putExtra("isFull", true)
                            intent.putExtra("url", t.terms)
                            intent.putExtra("title", resources.getString(com.yoo.module_res.R.string.user_agreement))
                            startActivity(intent)
                        }

                        override fun updateDrawState(ds: TextPaint) {
                            ds.isUnderlineText = true
                            ds.color = Color.WHITE
                            ds.clearShadowLayer()
                        }
                    }, 0, 14, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

                    style.setSpan(object : ClickableSpan() {
                        override fun onClick(p0: View) {
                            val intent = Intent(this@LoginActivity, RongWebviewActivity::class.java)
                            intent.putExtra("isFull", true)
                            intent.putExtra("url", t.privacyPolicy)
                            intent.putExtra(
                                "title",
                                resources.getString(com.yoo.module_res.R.string.privacy_policy)
                            )
                            startActivity(intent)
                        }

                        override fun updateDrawState(ds: TextPaint) {
                            ds.isUnderlineText = true
                            ds.color = Color.WHITE
                            ds.clearShadowLayer()
                        }
                    }, 17, style.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

                    binding.txtLoginAgreement.text = style
                    binding.txtLoginAgreement.movementMethod = LinkMovementMethod.getInstance()
                }

            }

        })
    }

    override fun initListener() {
        super.initListener()
        //谷歌登录
        binding.txtLoginGoogle.setOnClickCallback {
            showProgressDialog(this)
            val signInIntent: Intent = googleSignInClient.signInIntent
            startActivityForResult(signInIntent, GOOGLE_SIGN_IN)
        }
        //跳转到手机号登录
        binding.txtLoginPhoneNumber.setOnClickCallback {
            if (BuildConfig.DEBUG){
                PwdLoginActivity.start(this)
                return@setOnClickCallback
            }
            PhoneLoginActivity.start(this)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        hideProgressDialog()
        if (requestCode == GOOGLE_SIGN_IN && resultCode != 0) {//谷歌登录信息返回
            val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(data)
            handleSignInResult(task)
        } else if (requestCode == GOOGLE_SIGN_IN) {
            assert(data != null)
            ToastUtil.showToast(data.toString())
        }
    }

    /**
     * Google登录成功返回数据
     * @param completedTask
     */
    private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
        try {
            val account = completedTask.getResult(ApiException::class.java)
            mViewModel?.getLogin(object :HttpRequestListener<LoginResultModel>(){
                override fun addRequestParams(params: HashMap<String, Any>) {
                    account.account?.name?.let { params["account"]=it }
                    account.email?.let { params["email"]= it }
                    params["loginType"]="2"
                    account.displayName?.let { params["userName"]= it }
                }

                override fun success(t: LoginResultModel?) {
                    t?.apply {
                        SaveDeviceUtil.saveToken(t.token)
                        SaveDeviceUtil.saveUserCode(t.userCode)
                        SaveDeviceUtil.saveUserValid(t.isUserValid)
                        SaveDeviceUtil.saveAvatarUrl(t.avatarUrl)
                        SaveDeviceUtil.saveDeleteAccount(false)
                        if (t.isUserValid) {
                            MainActivity.start(this@LoginActivity)
                        }else{
                            RegisterActivity.start(this@LoginActivity)
                        }
                        finish()
                    }
                }

            })
        } catch (e: ApiException) {
        }
    }

}